package com.zhsj.OkeHomeConsumption.ui.activity.wallet;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.zhsj.OkeHomeConsumption.R;
import com.zhsj.OkeHomeConsumption.common.Constants;
import com.zhsj.OkeHomeConsumption.common.OkeHomeConsumptionApi;
import com.zhsj.OkeHomeConsumption.empty.FormalUserInfo;
import com.zhsj.OkeHomeConsumption.empty.Wallet;
import com.zhsj.OkeHomeConsumption.empty.WalletBean;
import com.zhsj.OkeHomeConsumption.network.HttpClient;
import com.zhsj.OkeHomeConsumption.network.JsonResponseHandler;
import com.zhsj.OkeHomeConsumption.other.TimeChecker;
import com.zhsj.OkeHomeConsumption.other.URLEntity;
import com.zhsj.OkeHomeConsumption.utils.LogUtils;
import com.zhsj.OkeHomeConsumption.utils.SignUtil;
import com.zhsj.OkeHomeConsumption.utils.Utils;

import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONTokener;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;


/**
 * Created by zwj on 2018/3/12.
 * 钱包明细
 */

public class WalletDetailFragment extends BaseFragment implements View.OnClickListener{

    // 左标题
    private TextView topbar_textview_leftitle = null;
    // 主标题
    private TextView topbar_textview_title = null;

    // 下拉刷新 上拉加载 更多控件
    private PullToRefreshListView refreshLayout;

    //加载页数
    private int pageNum = 0;


    /**
     * @Fields neterror_relative : TODO
     */
    private RelativeLayout neterror_relative = null;
    /**
     * @Fields btn_loadingrefresh : TODO
     */
    private Button btn_loadingrefresh = null;
    /**
     * 实例化ProgressDrawableAlertDialog
     */
    private ProgressDrawableAlertDialog pDialogUtils = null;

    /**
     * 计时器
     */
    private TimeChecker timeChecker = null;

    private WalletDetailAdapter mWalletDetailAdapter = null;
    private Wallet mWallet;
    private List<WalletBean> mWalletBeanList = null;
    private List<WalletBean> mWalletBeanServiceList = null;

    private FormalUserInfo userInfo;

    public static WalletDetailFragment newInstance(FormalUserInfo userInfo) {

        Bundle args = new Bundle();
        WalletDetailFragment fragment = new WalletDetailFragment();
        args.putSerializable("userInfo",userInfo);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        userInfo = (FormalUserInfo) getArguments().getSerializable("userInfo");
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.designing_project_fragment, container, false);
        initView(view);
        return view;
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        initData();
    }

    private void initView(View view) {
        // 初始化标题
        topbar_textview_leftitle = (TextView) view.findViewById(R.id.topbar_textview_leftitle);
        topbar_textview_title = (TextView) view.findViewById(R.id.topbar_textview_title);
        topbar_textview_leftitle.setVisibility(View.VISIBLE);
        topbar_textview_leftitle.setOnClickListener(this);
        // 设置标题内容
        topbar_textview_title.setText("收支明细");
        refreshLayout = (PullToRefreshListView) view.findViewById(R.id.subscription_list_view);
        //断网或者无网络状态下显示页面
        neterror_relative = (RelativeLayout) view.findViewById(R.id.neterror_relative);
        btn_loadingrefresh = (Button) view.findViewById(R.id.btn_loadingrefresh);
    }

    private void initData() {
        timeChecker = new TimeChecker(TimeOutHandler.timeOutHandler, Constants.TIME_OUT);
        pDialogUtils = new ProgressDrawableAlertDialog(getActivity());
        mWalletBeanList =  new ArrayList<WalletBean>();
        mWalletBeanServiceList =  new ArrayList<WalletBean>();
        mWalletDetailAdapter = new WalletDetailAdapter(getActivity(),mWalletBeanList);
        refreshLayout.setAdapter(mWalletDetailAdapter);

        if (!Utils.isNetWorkConnected(getActivity())) {
            //无网络的状态下
            neterror_relative.setVisibility(View.VISIBLE);
            refreshLayout.setVisibility(View.GONE);
            showShortToast("网络状态弱，请重试");
        } else {
            //有网络的状态下
            neterror_relative.setVisibility(View.GONE);
            refreshLayout.setVisibility(View.VISIBLE);
            // 钱包资金明细
            moneyDetail(userInfo.getId(), 0, 1000);

        }
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.topbar_textview_leftitle:
                _mActivity.onBackPressed();
                break;
            case R.id.btn_loadingrefresh:
                //唤醒网络
                if (!Utils.isNetWorkConnected(getActivity())) {
                    //无网络的状态下
                    neterror_relative.setVisibility(View.VISIBLE);
                    refreshLayout.setVisibility(View.GONE);
                    showShortToast("网络状态弱，请重试");
                } else {
                    //有网络的状态下
                    neterror_relative.setVisibility(View.GONE);
                    refreshLayout.setVisibility(View.VISIBLE);

                }
                break;
        }
    }

    public void moneyDetail(long userId, int page, int pagesize) {
        // TODO Auto-generated method stub
        // post传参使用的HashMap
        HashMap<String, String> paramMaps = new HashMap<String, String>();
        // 生成sign值所使用的HashMap
        final HashMap<String, String> mLogOnHashMap = new HashMap<String, String>();
        mLogOnHashMap.put("v", Constants.APPVERSION);
        mLogOnHashMap.put("t", Constants.TIME);
        LogUtils.e("LogOnPost time =", Constants.TIME);
        mLogOnHashMap.put("deviceId", URLEntity.getInstance().getImei());
        mLogOnHashMap.put("platform", Constants.PLAFORM);
        mLogOnHashMap.put("deviceToken", Constants.DEVICETOKEN);
        mLogOnHashMap.put("client", Constants.CLIENT);

        mLogOnHashMap.put("userId", String.valueOf(userId));
        mLogOnHashMap.put("page", String.valueOf(page));
        mLogOnHashMap.put("pagesize", String.valueOf(pagesize));

        paramMaps.put("userId", String.valueOf(userId));
        paramMaps.put("page", String.valueOf(page));
        paramMaps.put("pagesize", String.valueOf(pagesize));
        // 网络计时器及线程

        TimeOutHandler.pDialogUtils = pDialogUtils;
        pDialogUtils.show();
        timeChecker.start();
        // 获取sign签名
        Constants.SIGN = SignUtil.getInstance().getSign(mLogOnHashMap);
        HttpClient.post(OkeHomeConsumptionApi.MONEY_DETAIL, paramMaps, new JsonResponseHandler() {

            @Override
            public void onSuccess(int statusCode, String content) {
                // TODO Auto-generated method stub
                super.onSuccess(statusCode, content);
                timeChecker.check();
                pDialogUtils.dismiss();
                TimeOutHandler.pDialogUtils = null;
                LogUtils.e("content_钱包资金明细", content);
                try {
                    JSONTokener jsonT = new JSONTokener(content);
                    JSONObject jsonOBJ = (JSONObject) jsonT.nextValue();
                    String code = jsonOBJ.optString("code");
                    String message = jsonOBJ.optString("message");
                    if (code.equals("N000000")) {
                        com.alibaba.fastjson.JSONObject resultCode = JSON.parseObject(content);
                        com.alibaba.fastjson.JSONObject obJ = resultCode.getJSONObject("data");
                        mWallet = com.alibaba.fastjson.JSONObject.parseObject(obJ.toString(), Wallet.class);
                        mWalletBeanServiceList = mWallet.getData();
                        if (mWalletBeanServiceList != null){
                            mWalletBeanList.addAll(mWalletBeanServiceList);
                            mWalletDetailAdapter.notifyDataSetChanged();
                        }

                    } else if (code.equals(Constants.STATUSTOKENERROR)) {
                        // token过期
                        if (!message.equals("null")) {
                            showShortToast(message);
                        }
                    } else {
                        if (!message.equals("null")) {
                            showShortToast(message);
                        }
                    }
                } catch (JSONException ex) {
                    LogUtils.e("RegisterActivity", "sendcode异常 ");
                }finally {
                    //刷新或加载正在运行就关闭
                    if (refreshLayout.isRefreshing()){
//                        refreshLayout.postDelayed(new Runnable() {
//
//                            @Override
//                            public void run() {
                        refreshLayout.onRefreshComplete();
//                            }
//                        }, 1000);
                    }
                }

            }

            @Override
            public void onFailure(Throwable e) {
                // TODO Auto-generated method stub
                super.onFailure(e);
                timeChecker.check();
                pDialogUtils.dismiss();
                TimeOutHandler.pDialogUtils = null;
                LogUtils.e("onFailure", "" + e.toString());
                if (refreshLayout.isRefreshing()){
                    refreshLayout.postDelayed(new Runnable() {

                        @Override
                        public void run() {
                            refreshLayout.onRefreshComplete();
                        }
                    }, 1000);
                }
            }
        });
    }
}
